package com.wfs.suanfa.nio.demo.echo.nonio;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class NettyOioServer {


    public static  void server(int port) throws InterruptedException {
        ByteBuf buf = Unpooled.unreleasableBuffer(
                Unpooled.copiedBuffer("Hi\t\r", Charset.forName("UTF-8")));
        EventLoopGroup grop = new OioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(grop)
                    //使用OioEventLoopGroup以允许阻塞模式
                    .channel(OioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    //制定ChannelInitializer 对于每个接受的连接调用它
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(
                                    new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelActive(ChannelHandlerContext ctx) {
                                            ctx.writeAndFlush(buf.duplicate())
                                                    .addListener(ChannelFutureListener.CLOSE);
                                            System.err.println("服务端消息发送:");
                                        }
                                    }

                            );

                        }
                    });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            grop.shutdownGracefully().sync();
        }

    }

    public static void main(String[] args) {
        try {
            NettyOioServer.server(7001);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
